<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/6/1
 * Time: 16:53
 */

namespace app\api\controller;


use pay\Ali;
use pay\Wxservicer;
use think\Db;

class Classes extends Base
{
    public $user_id;
    public $create_time;
    public $page;
    public $err = '系统繁忙，请稍后重试';
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 课程分类列表
     * @return \think\response\Json
     */
    public function classCate(){
        $cate = Db::table('up_class_cate')
            ->where('c_cate_status', 1)
            ->field('c_cate_id, c_cate_name')
            ->order('c_cate_time desc')
            ->select();
        if($cate){
            return json(['status' => 200, 'msg' => $cate]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 选择感兴趣的课程分类
     * @return \think\response\Json
     * cate_ids      课程分类ID
     */
    public function chooseCate(){
        $cate_ids = input('cate_ids');
        $like = [
            'c_like_cate_id' => $cate_ids,
            'c_like_user_id' => $this->user_id
        ];
        $res = Db::table('up_class_like_cate')->insert($like);
        if($res){
            return json(['status' => 200, 'msg' => '选择成功']);
        }else{
            return json(['status' => 0, 'msg' => $this->err]);
        }
    }
    
    /**
     * 判断用户是否已经选择过课程分类
     * @return \think\response\Json
     *
     */
    public function haveChoosed(){
        $choosed = Db::table('up_class_like_cate')->where('c_like_user_id', $this->user_id)->find();
        if($choosed){
            $have = 1;
        }else{
            $have = 2;
        }
        return json(['status' => 200, 'msg' => $have]);
    }
    
    /**
     * 课程列表
     * @return \think\response\Json
     * show_type    列表展示页面    1 热门    2 兴趣   3 推荐     4 分类列表   5 免费课程
     * keyword      查询关键字
     * cate_id      分类ID
     */
    public function classList(){
        $show_type = input('show_type'); // 1 热门   2 兴趣   3 推荐   4 分类列表  5 免费课程
        $keyword = input('keyword'); // 关键字查询
        
        $where = $this->userWhere();
        $query = Db::table('up_class')
            ->field('class_id, class_title, class_type, class_price, class_apply_number, class_thumb')
            ->where($where);
        
        $order = 'class_create_time desc';
        $where1['class_status'] = 1;
        if(isset($keyword) && $keyword != '') $where1['class_title'] = ['like', '%' . $keyword . '%'];
        
        if($show_type != 2){
            if($show_type == 1){
                $where1['class_is_hot'] = 1;
            }else if($show_type == 3){
                $where1['class_is_recommend'] = 1;
            }else if($show_type == 4){
                $cate_id = input('cate_id');
                $where1['class_cate_id'] = $cate_id;
            }else{
                $where1['class_type'] = 1;
            }
            $class = $query->where($where1)->order($order)->page($this->page, 10)->select();
        }else{
            // 条件
            $like_cate = Db::table('up_class_like_cate')->where('c_like_user_id', $this->user_id)->value('c_like_cate_id');
            if($like_cate){
                $where1['class_cate_id'] = ['IN', $like_cate];
                // 排序
                $order_rule = Db::table('up_class_click')
                    ->where('c_click_user_id', $this->user_id)
                    ->order('c_click_number asc')
                    ->column('c_click_class_id');
                if($order_rule){
                    $order_ids = implode(',', $order_rule);
                    $query->orderRaw("FIELD(class_id, {$order_ids}) desc");
                }
                $class = $query->where($where1)->order($order)->page($this->page, 10)->select();
            }else{
                $class = [];
            }
        }
        
        // 课程积分
//        $integral = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_class_balance');
        if($class){
            if($show_type != 4 && $show_type != 5){
                foreach($class as $ke => $vo){
                    // 点赞数量
                    $dz_num = Db::table('up_class_dz')->where('c_dz_class_id', $vo['class_id'])->count();
                    // 收藏数量
                    $collect_num = Db::table('up_class_collect')->where('c_collect_class_id', $vo['class_id'])->count();
                    $class[$ke]['class_dz_number'] = $dz_num;
                    $class[$ke]['class_collect_number'] = $collect_num;
                }
            }
            return json([
                'status' => 200,
                'msg' => $class,
//                'integral' => $integral
            ]);
        }else{
            return json([
                'status' => 200,
                'msg' => [],
//                'integral' => $integral
            ]);
        }
    }
    
    /**
     * 课程轮播图
     * @return \think\response\Json
     * class_id       课程ID
     */
    public function classBanner(){
        $class_id = input('class_id');
        $images = Db::table('up_class')->where('class_id', $class_id)->field('class_images')->find();
        if($images){
            $images['class_images'] = explode(',', $images['class_images']);
            return json(['status' => 200, 'msg' => $images]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 课程介绍
     * @param $class_id    课程ID
     * @return \think\response\Json
     */
    public function classIntro(){
        $class_id = input('class_id');
        $intro = Db::table('up_class')
            ->where('class_id', $class_id)
            ->field('class_title, class_type, class_price, class_apply_number, class_intro, class_cate_id, 
            class_shiyong_user, class_teacher_name, class_teacher_image, class_teacher_intro, class_status')
            ->find();
        if(!$intro) return json(['status' => 0, 'msg' => '课程不存在']);
        if($intro['class_status'] == 2) return json(['status' => 0, 'msg' => '课程已下架']);
        
        // 如果是感兴趣课程，需要记录用户的点击量
        $like_cate_ids = Db::table('up_class_like_cate')->where('c_like_user_id', $this->user_id)->value('c_like_cate_id');
        if($like_cate_ids){
            $like_cate_id_arr = explode(',', $like_cate_ids);
            if(in_array($intro['class_cate_id'], $like_cate_id_arr)){
                $is_click = Db::table('up_class_click')
                    ->where(['c_click_user_id' => $this->user_id, 'c_click_class_id' => $class_id])
                    ->field('c_click_id')
                    ->find();
                if($is_click){
                    Db::table('up_class_click')->where('c_click_id', $is_click['c_click_id'])->setInc('c_click_number');
                }else{
                    Db::table('up_class_click')
                        ->insert([
                            'c_click_user_id' => $this->user_id,
                            'c_click_class_id' => $class_id
                        ]);
                }
            }
        }
        
        // 评价星级
        $ave_star = $this->commentStarLevel($class_id);
        $intro['ave_star'] = $ave_star;
        // 是否点赞
        $is_dz = $this->isDz($class_id);
        $intro['is_dz'] = $is_dz;
        // 是否收藏
        $is_collect = $this->isCollect($class_id);
        $intro['is_collect'] = $is_collect;
        // 点赞数量
        $dz_num = Db::table('up_class_dz')->where('c_dz_class_id', $class_id)->count();
        $intro['dz_num'] = $dz_num;
        // 收藏数量
        $collect_num = Db::table('up_class_collect')->where('c_collect_class_id', $class_id)->count();
        $intro['collect_num'] = $collect_num;
        return json(['status' => 200, 'msg' => $intro]);
    }
    
    /**
     * 相关课程
     * @param $class_id    课程ID
     * @return \think\response\Json
     */
    public function xgClass(){
        $class_id = input('class_id');
        $class_cate = Db::table('up_class')->where('class_id', $class_id)->value('class_cate_id');
        $class = Db::table('up_class')
            ->where(['class_status' => 1, 'class_cate_id' => $class_cate, 'class_id' => ['NEQ', $class_id]])
            ->where($this->userWhere())
            ->field('class_id, class_title, class_apply_number, class_thumb')
            ->order('class_create_time desc')
            ->page($this->page, 3)
            ->select();
        if($class){
            return json(['status' => 200, 'msg' => $class]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 点赞/取消点赞
     * @param $class_id     课程ID
     * @return \think\response\Json
     */
    public function doDz(){
        $class_id = input('class_id');
        $is_dz = Db::table('up_class_dz')->where(['c_dz_user_id' => $this->user_id, 'c_dz_class_id' => $class_id])->find();
        if($is_dz){
            $res = Db::table('up_class_dz')->where('c_dz_id', $is_dz['c_dz_id'])->delete();
        }else{
            $dz = ['c_dz_user_id' => $this->user_id, 'c_dz_class_id' => $class_id, 'c_dz_time' => $this->create_time];
            $res = Db::table('up_class_dz')->insert($dz);
        }
        if($res){
            return json(['status' => 200, 'msg' => 'success']);
        }else{
            return json(['status' => 0, 'msg' => $this->err]);
        }
    }
    
    /**
     * 收藏/取消收藏课程
     * @param $class_id     课程ID
     * @return \think\response\Json
     */
    public function doCollectClass(){
        $class_id = input('class_id');
        $is_collect = Db::table('up_class_collect')->where(['c_collect_user_id' => $this->user_id, 'c_collect_class_id' => $class_id])->find();
        if($is_collect){
            $res = Db::table('up_class_collect')->where('c_collect_id', $is_collect['c_collect_id'])->delete();
        }else{
            $collect = ['c_collect_user_id' => $this->user_id, 'c_collect_class_id' => $class_id, 'c_collect_time' => $this->create_time];
            $res = Db::table('up_class_collect')->insert($collect);
        }
        if($res){
            return json(['status' => 200, 'msg' => 'success']);
        }else{
            return json(['status' => 0, 'msg' => $this->err]);
        }
    }
    
    /**
     * 课程章节
     * @return \think\response\Json
     * class_id    课程ID
     */
    public function classSection(){
        $class_id = input('class_id');
        $class_video_audio = Db::table('up_class')->where('class_id', $class_id)->value('class_video_audio');
        $section = $this->sectionList($class_id);
        if($section){
            // 已观看时长
            foreach($section as $k => $v){
                $history = Db::table('up_class_history')
                    ->where(['c_history_section_id' => $v['c_section_id'], 'c_history_user_id' => $this->user_id])
                    ->field('c_history_look_time, c_history_rate')
                    ->find();
                if($history['c_history_look_time']){
                    $section[$k]['look_time'] = $history['c_history_look_time'];
                }else{
                    $section[$k]['look_time'] = 0;
                }
                $section[$k]['rate'] = $history['c_history_rate'];
            }
            return json(['status' => 200, 'msg' => $section, 'video_audio' => $class_video_audio]);
        }else{
            return json(['status' => 200, 'msg' => [], 'video_audio' => $class_video_audio]);
        }
    }
    
    /**
     * 评价课程
     * @return \think\response\Json
     * class_id     课程ID
     * c_comment_content    评价内容
     * c_comment_star       评价星级
     */
    public function commentClass(){
        $class_id = input('class_id');
        $c_comment_content = input('c_comment_content');
        $c_comment_star = input('c_comment_star');
        $look_number = Db::table('up_class_history')
            ->where(['c_history_class_id' => $class_id, 'c_history_user_id' => $this->user_id])
            ->count();
        $comment = [
            'c_comment_class_id' => $class_id,
            'c_comment_user_id' => $this->user_id,
            'c_comment_content' => $c_comment_content,
            'c_comment_star' => $c_comment_star,
            'c_comment_look_number' => $look_number,
            'c_comment_time' => $this->create_time
        ];
        $res = Db::table('up_class_comment')->insert($comment);
        if($res){
            return json(['status' => 200, 'msg' => '评价成功']);
        }else{
            return json(['status' => 0, 'msg' => $this->err]);
        }
    }
    
    /**
     * 判读用户是否可以评价课程
     * @return \think\response\Json
     * class_id      课程ID
     */
    public function canComment(){
        $class_id = input('class_id');
        // 是否已经评价过
        $have_comment = Db::table('up_class_comment')
            ->where(['c_comment_class_id' => $class_id, 'c_comment_user_id' => $this->user_id])
            ->field('c_comment_star')
            ->find();
        if($have_comment){
            $commented = 1;
        }else{
            $commented = 2;
        }
        // 是否已经购买该课程
        $have_apply = Db::table('up_class_apply')
            ->where(['c_apply_user_id' => $this->user_id, 'c_apply_class_id' => $class_id])
            ->find();
        if($have_apply){
            $applyed = 1;
        }else{
            $applyed = 2;
        }
        return json(['status' => 200, 'msg' => '', 'commented' => $commented, 'applyed' => $applyed, 'comment_star' => $have_comment['c_comment_star']]);
    }
    
    /**
     * 评论列表
     * @return \think\response\Json
     * class_id    课程ID
     */
    public function commentList(){
        $class_id = input('class_id');
        $commentList = [];
        // 平均星级
        $ave_star = $this->commentStarLevel($class_id);
        // 每个星级占比
        $one_star = $this->starPro($class_id, 1);
        $two_star = $this->starPro($class_id, 2);
        $three_star = $this->starPro($class_id, 3);
        $four_star = $this->starPro($class_id, 4);
        $five_star = $this->starPro($class_id, 5);
        $commentList['ave_star'] = $ave_star;
        $commentList['one_star'] = $one_star;
        $commentList['two_star'] = $two_star;
        $commentList['three_star'] = $three_star;
        $commentList['four_star'] = $four_star;
        $commentList['five_star'] = $five_star;
        // 评价列表
        $comment = Db::table('up_class_comment')
            ->join('up_u_user', 'user_id = c_comment_user_id', 'LEFT')
            ->where(['c_comment_class_id' => $class_id, 'c_comment_status' => 1])
            ->field('c_comment_id, user_username, user_image, c_comment_content, c_comment_star,
             c_comment_time, c_comment_look_number')
            ->page($this->page, 10)
            ->order('c_comment_time desc')
            ->select();
        if($comment){
//            foreach($comment as $k => $v){
//                // 评价是观看的章节数量
//                $look_number = Db::table('up_class_history')
//                    ->where(['c_history_class_id' => $class_id, 'c_history_user_id' => $this->user_id])
//                    ->count();
//                $comment[$k]['look_number'] = $look_number;
//                // 回复
//                $reply = Db::table('up_class_reply')
//                    ->where(['c_reply_comment_id' => $v['c_comment_id'], 'c_reply_status' => 1])
//                    ->field('c_reply_id, c_reply_type, c_reply_user_id, c_reply_admin_id, c_reply_content,
//                    c_reply_from, c_reply_time, c_reply_reply_id')
//                    ->order('c_reply_time desc')
////                    ->page($this->page, 10)
//                    ->select();
//                if($reply){
//                    foreach($reply as $kk => $vv){
//                        // 如果回复的是回复
//                        if($vv['c_reply_type'] == 2){
//                            $to_user = Db::table('up_class_reply')
//                                ->where('c_reply_id', $vv['c_reply_reply_id'])
//                                ->field('c_reply_from, c_reply_user_id, c_reply_admin_id')
//                                ->find();
//                            if($to_user['c_reply_from'] == 1){ // 回复的是app用户
//                                $reply_to_user = Db::table('up_u_user')
//                                    ->where('user_id', $to_user['c_reply_user_id'])
//                                    ->field('user_id id, user_username username')
//                                    ->find();
//                            }else{
//                                $reply_to_user = Db::table('up_admin')
//                                    ->where('id', $to_user['c_reply_admin_id'])
//                                    ->field('id, username')
//                                    ->find();
//                            }
//                            $reply[$kk]['to_username'] = $reply_to_user['username'];
//                            $reply[$kk]['to_user_id'] = $reply_to_user['id'];
//                        }
//
//                        // 谁回复的
//                        if($vv['c_reply_from'] == 1){
//                            $reply_user = Db::table('up_u_user')
//                                ->where('user_id', $vv['c_reply_user_id'])
//                                ->field('user_id id, user_username username')
//                                ->find();
//                        }else{
//                            $reply_user = Db::table('up_admin')
//                                ->where('id', $vv['c_reply_admin_id'])
//                                ->field('id, username')
//                                ->find();
//                        }
//                        $reply[$kk]['user_username'] = $reply_user['username'];
//                    }
//                    $comment[$k]['reply'] = $reply;
//                }else{
//                    $comment[$k]['reply'] = [];
//                }
//            }
            $commentList['comment'] = $comment;
        }else{
            $commentList['comment'] = [];
        }
        return json(['status' => 200, 'msg' => $commentList]);
    }
    
    /**
     * 回复评论
     * @return \think\response\Json
     * comment_id      被评论ID
     * reply_content    回复内容
     */
    public function replyComment(){
        $comment_id = input('comment_id');
        $reply_content = input('reply_content');
        $class_id = Db::table('up_class_comment')->where('c_comment_id', $comment_id)->value('c_comment_class_id');
        
        $reply = [
            'c_reply_type' => 1,
            'c_reply_user_id' => $this->user_id,
            'c_reply_admin_id' => 0,
            'c_reply_comment_id' => $comment_id,
            'c_reply_class_id' => $class_id,
            'c_reply_reply_id' => 0,
            'c_reply_content' => $reply_content,
            'c_reply_from' => 1,
            'c_reply_time' => $this->create_time
        ];
        $res = Db::table('up_class_reply')->insert($reply);
        if($res){
            return json(['status' => 200, 'msg' => '回复成功']);
        }else{
            return json(['status' => 0, 'msg' => '回复失败']);
        }
    }
    
    /**
     * 回复回复
     * @return \think\response\Json
     * reply_id      被回复的ID
     * reply_content    回复内容
     */
    public function replyReply(){
        $reply_id = input('reply_id');
        $reply_content = input('reply_content');
        $class_id = Db::table('up_class_reply')->where('c_reply_id', $reply_id)->value('c_reply_class_id');
    
        $reply = [
            'c_reply_type' => 2,
            'c_reply_user_id' => $this->user_id,
            'c_reply_admin_id' => 0,
            'c_reply_comment_id' => 0,
            'c_reply_class_id' => $class_id,
            'c_reply_reply_id' => $reply_id,
            'c_reply_content' => $reply_content,
            'c_reply_from' => 1,
            'c_reply_time' => $this->create_time
        ];
        $res = Db::table('up_class_reply')->insert($reply);
        if($res){
            return json(['status' => 200, 'msg' => '回复成功']);
        }else{
            return json(['status' => 0, 'msg' => '回复失败']);
        }
    }
    
    /**
     * 判断是否需要报名课程，无论课程收费还是免费
     * @return \think\response\Json
     * class_id      课程ID
     */
    public function needBuy(){
        $class_id = input('class_id');
        $need_buy = $this->needBuyClass($class_id);
        $class = Db::table('up_class')
            ->where('class_id', $class_id)
            ->field('class_type, class_price')
            ->find();
        return json(['status' => 200, 'msg' => $need_buy, 'class' => $class]);
    }
    
    /**
     * 确认支付页面展示
     * @return \think\response\Json
     * class_id     课程ID
     */
    public function showPay(){
        $class_id = input('class_id');
        $class = Db::table('up_class')
            ->where('class_id', $class_id)
            ->field('class_id, class_type, class_price, class_title, class_thumb, class_is_forever, 
            class_valid_date')
            ->find();
        if($class['class_is_forever'] == 1){
            $valid_date = date('Y年m月d日', strtotime("+{$class['class_valid_date']}days"));
        }else{
            $valid_date = '永久';
        }
        $class['valid_date'] = $valid_date;
//        // 剩余积分
//        $integral = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_class_balance');
//        $class['integral'] = $integral;
        
        return json(['status' => 200, 'msg' => $class]);
    }
    
    /**
     * 判断用户是否有该课程未付款的订单----暂时不用
     * @return \think\response\Json
     * class_id     课程ID
     */
    public function haveUnpayOrder(){
        $class_id = input('class_id');
        $have = Db::table('up_class_order')
            ->where(['co_user_id' => $this->user_id, 'co_class_id' => $class_id, 'order_is_pay' => 1])
            ->field('order_id')
            ->find();
        if($have){
            return json(['status' => 200, 'msg' => 1, 'order_id' => $have['order_id']]);
        }else{
            return json(['status' => 200, 'msg' => 2, 'order_id' => '']);
        }
    }
    
    /**
     * 创建订单
     * @return \think\response\Json
     * class_id      课程ID
     */
    public function createOrder(){
        $class_id = input('class_id');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);
        $need_buy = $this->needBuyClass($class_id);
        if($need_buy == 1) return json(['status' => 0, 'msg' => '您暂时不需要购买此课程，可直接观看']);

        $haveBuy = Db::table('up_class_order')
            ->where(['co_user_id' => $this->user_id, 'co_class_id' => $class_id, 'co_is_pay' => 1])
            ->field('co_id')
            ->find();
        $order_num = 'KC_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($haveBuy){
            $order_id = $haveBuy['co_id'];
            $res = Db::table('up_class_order')->where('co_id', $order_id)->setField('co_number', $order_num);
            if($res){
                return json(['status' => 200, 'msg' => '', 'order_id' => $order_id]);
            }else{
                return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            }
        }else{
            $class = Db::table('up_class')->where('class_id', $class_id)
                ->field('class_type, class_price')
                ->find();
            $insert = [
                'co_user_id' => $this->user_id,
                'co_class_id' => $class_id,
                'co_number' => $order_num,
                'co_create_time' => $this->create_time
            ];
            $order_price = 0;
            if($class['class_type'] == 2){
                $order_price = $class['class_price'];
            }
            $insert['co_total_price'] = $order_price;
            $order_id = Db::table('up_class_order')->insertGetId($insert);
            if($order_id){
                return json(['status' => 200, 'msg' => '', 'order_id' => $order_id]);
            }else{
                return json(['status' => 0, 'msg' => $this->err]);
            }
        }
    }
    
    /**
     * 确认支付
     * @return \think\response\Json
     * class_code         兑换码
     * order_id           订单ID
     * pay_type           支付方式  2 微信   3 支付宝   4 兑换码   5 免费
     */
    public function commitPay(){
        $order_id = input('order_id');
        $class_code = trim(input('class_code'));
        $pay_type = input('pay_type'); // 支付方式  2 微信  3 支付宝   4 兑换码   5 免费
        
        $order = Db::table('up_class_order')->where('co_id', $order_id)
            ->field('co_user_id, co_class_id, co_total_price, co_is_pay, co_number')
            ->find();
        if($order['co_is_pay'] != 1) return json(['status' => 0, 'msg' => '订单状态异常']);

        $class = Db::table('up_class')->where('class_id', $order['co_class_id'])
            ->field('class_is_forever, class_valid_date')
            ->find();
        
        $haveClassCode = Db::table('up_class_code')->field('cc_id, cc_is_use')->where('cc_code', $class_code)->find();
        if($pay_type == 4){
            if(!$haveClassCode) return json(['status' => 0, 'msg' => '兑换码不存在']);
            if($haveClassCode['cc_is_use'] == 2) return json(['status' => 0, 'msg' => '兑换码已使用']);
        }

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);
        
        Db::startTrans();
        try{
            $update_order = ['co_id' => $order_id, 'co_pay_type' => $pay_type];

            if($pay_type == 2 || $pay_type == 3){ // 微信||支付宝
                Db::table('up_class_order')->update($update_order);

                if($pay_type == 2){
                    $wxConfig = config('wechat_servicer');
                    $wxConfig['sub_mchid'] = $mchid['mch_code'];
                    $wx = new Wxservicer($wxConfig);
                    $return = $wx->WeChatPayReadyServicerV2($order['co_total_price'], $order['co_number'], '购买课程');
                }else{
                    $ali = new Ali(config('ali'));
                    $return = $ali->getParam($order['co_number'], $order['co_total_price'], '课程', '购买课程');
                }

                if($return['status'] == 200){
                    Db::commit();
                    return json(['status' => 200, 'msg' => $return['message'], 'order_id' => $order_id, 'price' => $order['co_total_price']]);
                }else{
                    Db::rollback();
                    return json(['status' => 0, 'msg' => $return['message']]);
                }
            }elseif($pay_type == 4 || $pay_type == 5){ // 兑换码||免费
                if($pay_type == 4){
                    // 更新兑换码状态
                    Db::table('up_class_code')->update([
                        'cc_id' => $haveClassCode['cc_id'],
                        'cc_is_use' => 2,
                        'cc_use_user_id' => $this->user_id,
                        'cc_use_time' => $this->create_time
                    ]);
                }

                // 更新订单兑换码
                $update_order['co_class_code'] = $class_code;
                $update_order['co_is_pay'] = 2;
                $update_order['co_pay_time'] = $this->create_time;
                Db::table('up_class_order')->update($update_order);

                // 是否已经在报名表中，如果不在插入我报名的课程表&增加课程报名人数，如果在，就更新有效时间
                $have_apply = Db::table('up_class_apply')
                    ->where(['c_apply_user_id' => $this->user_id, 'c_apply_class_id' => $order['co_class_id']])
                    ->field('c_apply_id, c_apply_class_forever')
                    ->find();
                if($class['class_is_forever'] == 1){
                    $valid_date = date('Y-m-d', strtotime("+{$class['class_valid_date']}days"));
                }else{
//                    $valid_date = 0;
                    $valid_date = '';
                }
                if($have_apply){
                    $update_apply = [
                        'c_apply_class_forever' => $class['class_is_forever'],
                        'c_apply_update_time' => $this->create_time,
                        'c_apply_valid' => $valid_date
                    ];
                    // 更新有效期
                    Db::table('up_class_apply')->where('c_apply_id', $have_apply['c_apply_id'])->update($update_apply);
                }else{
                    // 插入报名表
                    $apply = [
                        'c_apply_user_id' => $this->user_id,
                        'c_apply_class_id' => $order['co_class_id'],
                        'c_apply_class_forever' => $class['class_is_forever'],
                        'c_apply_valid' => $valid_date,
                        'c_apply_time' => $this->create_time
                    ];
                    Db::table('up_class_apply')->insert($apply);

                    // 更新报名人数
                    Db::table('up_class')->where('class_id', $order['co_class_id'])->setInc('class_apply_number');
                }

                Db::commit();
                return json(['status' => 200, 'msg' => '购买成功']);
            }else{
                return json(['status' => 200, 'msg' => '购买成功']);
            }

        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
        
    }
    
    /**
     * 我购买的课程
     * @return \think\response\Json
     * page     页码
     */
    public function haveBuyClass(){
        $class = Db::table('up_class_apply')
            ->join('up_class', 'c_apply_class_id = class_id', 'LEFT')
            ->where('c_apply_user_id', $this->user_id)
            ->field('class_id, class_title, class_section_number, c_apply_valid, c_apply_class_forever')
            ->page($this->page, 10)
            ->order('c_apply_time desc')
            ->select();
        if($class){
            return json(['status' => 200, 'msg' => $class]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 章节播放页面
     * @return \think\response\Json
     * section_id    章节ID
     */
    public function playSection(){
        $section_id = input('section_id');
        $info = [];
    
        // 章节详情
        $section_info = Db::table('up_class_section')
            ->where('c_section_id', $section_id)
            ->field('c_section_class_id, c_section_id, c_section_url, c_section_name, c_section_detail')
            ->find();
        $info['section'] = $section_info;
        
        // 课程信息
        $class = Db::table('up_class')
            ->where('class_id', $section_info['c_section_class_id'])
            ->field('class_id, class_title, class_section_number')
            ->find();
        $info['class'] = $class;
        
        // 章节列表信息
        $section_list = $this->sectionList($section_info['c_section_class_id']);
        if($section_list){
            // 观看历史
            foreach($section_list as $k => $v){
                $history = Db::table('up_class_history')
                    ->where(['c_history_section_id' => $v['c_section_id'], 'c_history_user_id' => $this->user_id])
                    ->field('c_history_rate, c_history_look_time')
                    ->find();
                if($history){
                    $section_list[$k]['rate'] = $history['c_history_rate'];
                    $section_list[$k]['look_time'] = $history['c_history_look_time'];
                }else{
                    $section_list[$k]['rate'] = 0;
                    $section_list[$k]['look_time'] = 0;
                }
                
            }
            $info['sectionList'] = $section_list;
        }else{
            $info['sectionList'] = [];
        }
        
        // 是否收藏
        $is_collect = Db::table('up_class_collect_section')
            ->where(['c_collect_s_section_id' => $section_id, 'c_collect_s_user_id' => $this->user_id])
            ->find();
        if($is_collect){
            $info['is_collect'] = 1;
        }else{
            $info['is_collect'] = 2;
        }
        return json(['status' => 200, 'msg' => $info]);
    }
    
    /**
     * 收藏/取消收藏章节
     * @return \think\response\Json
     * section_id     章节ID
     */
    public function doCollectSection(){
        $section_id = input('section_id');
        $collect = Db::table('up_class_collect_section')
            ->where(['c_collect_s_section_id' => $section_id, 'c_collect_s_user_id' => $this->user_id])
            ->find();
        if($collect){
            $res = Db::table('up_class_collect_section')->where('c_collect_s_id', $collect['c_collect_s_id'])->delete();
        }else{
            $insert = [
                'c_collect_s_section_id' => $section_id,
                'c_collect_s_user_id' => $this->user_id,
                'c_collect_s_time' => $this->create_time
            ];
            $res = Db::table('up_class_collect_section')->insert($insert);
        }
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 记录章节观看历史
     * @return \think\response\Json
     * section_id      章节ID
     * look_time        观看时长
     */
    public function sectionHistory(){
        $section_id = input('section_id');
        $look_time = input('look_time'); // 观看时长
        $section = Db::table('up_class_section')
            ->where('c_section_id', $section_id)
            ->field('c_section_class_id, c_section_duration')
            ->find();
        $time_arr = explode(':', $section['c_section_duration']);
        $total_time_s = $time_arr[0] * 60 + $time_arr[1]; // 总时长
        $rate = number_format($look_time/$total_time_s, 3) * 100; // 进度
        
        $have_look = Db::table('up_class_history')
            ->where(['c_history_section_id' => $section_id, 'c_history_user_id' => $this->user_id])
            ->field('c_history_id')
            ->find();
        
        if($have_look){
            $update = ['c_history_look_time' => $look_time, 'c_history_rate' => $rate, 'c_history_time' => $this->create_time];
            $res = Db::table('up_class_history')->where('c_history_id', $have_look['c_history_id'])->update($update);
        }else{
            $insert = [
                'c_history_section_id' => $section_id,
                'c_history_class_id' => $section['c_section_class_id'],
                'c_history_user_id' => $this->user_id,
                'c_history_look_time' => $look_time,
                'c_history_rate' => $rate,
                'c_history_time' => $this->create_time
            ];
            $res = Db::table('up_class_history')->insert($insert);
        }
        if($res){
            return json(['status' => 200, 'msg' => true]);
        }else{
            return json(['status' => 0, 'msg' => false]);
        }
    }
    
    //********************************************  公共方法
    /**
     * 查询条件----根据用户角色匹配可以观看的课程
     * @return string
     */
    private function userWhere(){
        $where = '';
        $user_rule = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_rule');
        $rule = explode(',', $user_rule);
        foreach($rule as $k => $v){
            $where .= ($where ? ' or ' : '') . " FIND_IN_SET('$v', class_user_rule)";
        }
        return $where;
    }
    
    /**
     * 评论的平均星级
     * @param $class_id      课程ID
     * @return int|string
     */
    private function commentStarLevel($class_id){
        $star = Db::table('up_class_comment')
            ->field('sum(c_comment_star) star_number, count(c_comment_id) comment_number')
            ->where('c_comment_class_id', $class_id)
            ->find();
        if($star['comment_number']){
            $ave_star = number_format($star['star_number']/$star['comment_number'], 1);
        }else{
            $ave_star = 0;
        }
        return $ave_star;
    }
    
    /**
     * 不同星级的比例
     * @param $class_id    课程ID
     * @param $star_level  1 一星   2 二星  3 三星  4 四星  5 五星
     * @return int|string
     */
    private function starPro($class_id, $star_level){
        // 总共记录数
        $total_star = Db::table('up_class_comment')->where('c_comment_class_id', $class_id)->count();
        // 不同星级的记录数
        $diff_star = Db::table('up_class_comment')
            ->where(['c_comment_class_id' => $class_id, 'c_comment_star' => $star_level])
            ->count();
        $pro = 0;
        if($total_star !== 0){
            $pro = number_format($diff_star/$total_star, 4) * 100;
        }
        return $pro;
    }
    
    /**
     * 是否给课程点赞
     * @param $class_id     课程ID
     * @return int     1 已点赞    2 未点赞
     */
    private function isDz($class_id){
        $dz = Db::table('up_class_dz')
            ->where(['c_dz_user_id' => $this->user_id, 'c_dz_class_id' => $class_id])
            ->find();
        if($dz){
            $is_dz = 1;
        }else{
            $is_dz = 2;
        }
        return $is_dz;
    }
    
    /**
     * 是否已经收藏课程
     * @param $class_id    课程ID
     * @return int      1 已收藏    2 未收藏
     */
    private function isCollect($class_id){
        $collect = Db::table('up_class_collect')
            ->where(['c_collect_user_id' => $this->user_id, 'c_collect_class_id' => $class_id])
            ->find();
        if($collect){
            $is_collect = 1;
        }else{
            $is_collect = 2;
        }
        return $is_collect;
    }
    
    /**
     * 课程章节列表
     * @param $class_id     课程ID
     * @return false|\PDOStatement|string|\think\Collection
     */
    private function sectionList($class_id){
        $section = Db::table('up_class_section')
            ->where(['c_section_class_id' => $class_id, 'c_section_status' => 1])
            ->field('c_section_id, c_section_name, c_section_sort, c_section_url, c_section_duration')
            ->order('c_section_sort asc')
            ->select();
        return $section;
    }
    
    /**
     * 判断用户是否需要购买该课程
     * @param $class_id     课程ID
     * @return int    1 不需要购买    2 需要购买
     */
    private function needBuyClass($class_id){
        $need_buy = 1; // 不需要报名
    
        // 无论课程是收费还是免费，都进行判断
        $is_buy = Db::table('up_class_apply')
            ->where(['c_apply_user_id' => $this->user_id, 'c_apply_class_id' => $class_id])
            ->field('c_apply_class_forever, c_apply_valid')
            ->find();
        if($is_buy){
            $date_time = strtotime(date('Y-m-d'));
            $valid_time = strtotime($is_buy['c_apply_valid']);
            $class = Db::table('up_class')->field('class_is_forever')->where('class_id', $class_id)->find();
            if($is_buy['c_apply_class_forever'] == 1 && $class['class_is_forever'] == 1 && ($date_time > $valid_time)) $need_buy = 2;
            if($is_buy['c_apply_class_forever'] == 1 && $class['class_is_forever'] == 2 && ($date_time > $valid_time)) $need_buy = 2;
            if($is_buy['c_apply_class_forever'] == 2 && $class['class_is_forever'] == 1) $need_buy = 2;
//            if($class['class_is_forever'] == 1 && ($date_time > $valid_time)){
//                $need_buy = 2;
//            }
        }else{
            $need_buy = 2;
        }
        return $need_buy;
    }
}